package com.naiterui.ehp.bs.cms.modules.agent.service.impl;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.naiterui.ehp.bp.utils.date.DateUtil;
import com.naiterui.ehp.bs.cms.common.utils.ReportUtil;
import com.naiterui.ehp.bs.cms.common.vo.PageParamsVO;
import com.naiterui.ehp.bs.cms.common.vo.PageVO;
import com.naiterui.ehp.bs.cms.modules.agent.entity.AgAgentCustom;
import com.naiterui.ehp.bs.cms.modules.agent.mapper.AgAgentCustomMapper;
import com.naiterui.ehp.bs.cms.modules.agent.po.FindCustomPO;
import com.naiterui.ehp.bs.cms.modules.agent.service.ICustomService;
import com.naiterui.ehp.bs.cms.modules.agent.vo.CustomDailyVO;
import com.naiterui.ehp.bs.cms.modules.agent.vo.CustomExcelVO;
import com.naiterui.ehp.bs.cms.modules.agent.vo.CustomPageItemVO;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author yiren
 * @since 2022/2/16
 */
@Slf4j
@Service
public class CustomServiceImpl extends ServiceImpl<AgAgentCustomMapper, AgAgentCustom> implements ICustomService {

    @Override
    public PageVO<CustomPageItemVO> queryPage(PageParamsVO pageParamsVO, FindCustomPO pagePO) {

        QueryWrapper<FindCustomPO> entityWrapper = this.buildEntityWrapper(pageParamsVO, pagePO);

        IPage<CustomPageItemVO> page = this.baseMapper.getPage(pageParamsVO.getPage(), entityWrapper);

        return PageVO.toPageVo(page);
    }

    @Override
    public byte[] customExport(String doctorIds, String startDate, String endDate) throws IOException {
        List<Map<String, Object>> sheetsList = new ArrayList<>();
        if (StrUtil.isNotBlank(doctorIds)) {
            String[] doctorIdArr = doctorIds.split(",");
            List<String> doctorIdList = Arrays.asList(doctorIdArr);
            List<CustomDailyVO> customDailyList = this.baseMapper.exportCustom(doctorIdList, startDate, endDate);
            if (CollUtil.isNotEmpty(customDailyList)) {
                Map<Long, List<CustomDailyVO>> customMap =
                    customDailyList.stream().collect(Collectors.groupingBy(CustomDailyVO::getDoctorId));
                for (Map.Entry<Long, List<CustomDailyVO>> m : customMap.entrySet()) {
                    List<CustomDailyVO> customList = m.getValue();
                    if (CollUtil.isEmpty(customList)) {
                        continue;
                    }
                    ExportParams exportParams = new ExportParams();
                    exportParams.setSheetName("医生Id" + m.getKey());
                    exportParams.setTitle("医生Id" + m.getKey());
                    // 创建sheet1使用得map
                    Map<String, Object> exportMap = new HashMap<>();
                    // title的参数为ExportParams类型，目前仅仅在ExportParams中设置了sheetName
                    exportMap.put("title", exportParams);
                    // 模版导出对应得实体类型
                    exportMap.put("entity", CustomExcelVO.class);
                    List<CustomExcelVO> list = customList.stream().map(c -> {
                        CustomExcelVO excel = new CustomExcelVO();
                        excel.setReportDate(c.getGenerateDate());
                        excel.setPatientTotal(c.getPatientTotal());
                        excel.setConsultTotal(c.getConsultTotal());
                        excel.setRecipelTotal(c.getRecipelTotal());
                        excel.setRepeatTotal(c.getRepeatTotal());
                        excel.setOrderPriceTotal(ReportUtil.changeF2Y(c.getOrderPriceTotal()));
                        return excel;
                    }).collect(Collectors.toList());
                    // sheet中要填充得数据
                    exportMap.put("data", list);
                    sheetsList.add(exportMap);
                }
            }
        }
        Workbook workbook = ExcelExportUtil.exportExcel(sheetsList, ExcelType.HSSF);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);
        return byteArrayOutputStream.toByteArray();
    }

    private QueryWrapper<FindCustomPO> buildEntityWrapper(PageParamsVO pageParamsVO, FindCustomPO pagePO) {

        QueryWrapper<FindCustomPO> entityWrapper = pageParamsVO.getEntityWrapper("c");

        if (pagePO == null) {
            return entityWrapper;
        }
        entityWrapper.eq(pagePO.getAgentId() != null, "c.agent_id", pagePO.getAgentId())
            .eq(pagePO.getDoctorId() != null, "c.doctor_id", pagePO.getDoctorId())
            .like(StringUtils.isNotEmpty(pagePO.getDoctorName()), "d.name", pagePO.getDoctorName())
            .eq(StringUtils.isNotEmpty(pagePO.getDoctorPhone()), "d.phone", pagePO.getDoctorPhone());

        String startTime = pagePO.getEntryTimeGte();
        String endTime = pagePO.getEntryTimeLte();
        if (StringUtils.isNotEmpty(endTime)) {
            endTime += " " + DateUtil.MAX_TIME_IN_DAY;
        }
        entityWrapper.between(!StringUtils.isAnyEmpty(startTime, endTime), "d.created_at", startTime, endTime);

        return entityWrapper;
    }
}
